import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.apache.ibatis.session.SqlSessionManager;
import org.gwc.mapper.UserMapper;
import org.gwc.pojo.User;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

public class TsetCRUD {

    private SqlSession sqlSession;

    @BeforeEach // 每个测试方法执行之前都需执行的方法
    public void before() throws IOException {
        InputStream resourceAsStream = Resources.getResourceAsStream("mybatis-config.xml");
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
        sqlSession = sqlSessionFactory.openSession(true); // 自动提交事务
    }

    @AfterEach // 每个测试方法执行之后都需执行的方法
    public void after(){
        sqlSession.close();
    }

    @Test
    public void testInsert(){
        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
        User user = new User();
        user.setUsername("zyh");
        user.setPassword("123456");
        int inserted = userMapper.insert(user);
        System.out.println("插入数据的id = " + user.getId());
    }
    
    @Test
    public void testSelectAll(){
        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
        List<User> users = userMapper.selectAll();
        System.out.println("users = " + users);
    }

    @Test
    public void testUpdate(){
        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
        User user = userMapper.selectById(2);
        user.setPassword("111111");
        int updated = userMapper.update(user);
        List<User> users = userMapper.selectAll();
        System.out.println("users = " + users);
    }

    @Test
    public void testDelete(){
        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
        int deleted = userMapper.delete(1);
        List<User> users = userMapper.selectAll();
        System.out.println("users = " + users);
    }
}
